package io.gitee.zhangbinhub.acp.boot

import io.gitee.zhangbinhub.acp.boot.conf.AcpCorsConfiguration
import io.gitee.zhangbinhub.acp.boot.constant.AcpCoreConstant
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication
import org.springframework.context.annotation.Bean
import org.springframework.core.annotation.Order
import org.springframework.web.cors.reactive.CorsWebFilter
import org.springframework.web.filter.CorsFilter

@AutoConfiguration(after = [AcpPropertiesAutoConfiguration::class])
@ConditionalOnExpression($$"'${$${AcpCoreConstant.CORS_PREFIX}.enabled}'.equals('true')")
class AcpBootCorsAutoConfiguration(private val acpCorsConfiguration: AcpCorsConfiguration) {
    @Bean
    @Order(AcpCoreConstant.CORS_FILTER_ORDER)
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    fun corsFilter(): CorsFilter {
        return CorsFilter(acpCorsConfiguration.getServletCorsConfigurationSource())
    }

    @Bean
    @Order(AcpCoreConstant.CORS_FILTER_ORDER)
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
    fun corsWebFilter(): CorsWebFilter {
        return CorsWebFilter(acpCorsConfiguration.getReactiveCorsConfigurationSource())
    }
}